package com.dkcrow.lock.service.impl;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import com.dkcrow.lock.dao.UserDaoImpl;

@Service
public class UserServiceImpl{
	
	final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired UserDaoImpl userDaoImpl;
	
	@Transactional(propagation=Propagation.REQUIRED)
	public void excute(){
		
		insertElements(0);
		logger.info("######################################insert 끝!!");
		
		Callable<String>callable = new Callable<String>(){
			public String call() throws Exception {
				logger.info("######################################start thread!!");
				userDaoImpl.updateUser("1", "1111", 111);
				logger.info("######################################end thread!!");
				return null;
			}
		};
		
		FutureTask<String> future = new FutureTask<String>(callable);
		future.run();
		try {
			future.get();
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		} catch (ExecutionException e1) {
			e1.printStackTrace();
		}
		
		try {
			Thread.sleep(60*1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	private void insertElements(int start) {
		logger.info("현재 트랜잭션 use : {} \t name : {}",TransactionSynchronizationManager.isActualTransactionActive(),TransactionSynchronizationManager.getCurrentTransactionName());
		for(int i=start;i<start+10;i++){
			String id = "id"+i;
			String name="홀길동"+i;
			int age=i;
			userDaoImpl.insertUser(id,name,age);
		}
	}
	
	public void deleteAllUser(){
		userDaoImpl.deleteAllUser();
	}
}
